{include file="admin@public/header" /}

<link href="/public/static/admin/blue/bills.css?ver=20210803202401" rel="stylesheet" type="text/css">

<script src="/public/static/admin/js/common/base.js"></script>
<link rel="stylesheet" href="/public/static/admin/easyui/layui-v2.6.8/css/layui.css">

<style>
    /*#barCodeInsert{margin-left: 10px;font-weight: 100;font-size: 12px;color: #fff;background-color: #B1B1B1;padding: 0 5px;border-radius: 2px;line-height: 19px;height: 20px;display: inline-block;}*/
    /*#barCodeInsert.active{background-color: #23B317;}*/
    .shadow.opera-log-box::before,
    .shadow.opera-log-box::after {
        border: solid transparent;
        content: ' ';
        height: 0;
        bottom: 100%;
        position: absolute;
        width: 0;
    }

    .shadow.opera-log-box:after {
        border-width: 8px;
        border-bottom-color: #FFEED4;
        right: 60px;
    }

    .shadow.opera-log-box:before {
        border-width: 10px;
        border-bottom-color: #E1B77E;
        right: 58px;
    }
</style>

<div class="wrapper">
    <!-- <span id="config" class="ui-icon ui-state-default ui-icon-config"></span> -->
    <div class="mod-toolbar-top mr0 cf dn" id="toolTop"></div>
    <div class="bills cf">
        <div class="con-header">
            <dl class="cf">
                <dd>
                    <label>单据日期：</label>
                    <input type="date" id="date" class="ui-input" value="{$info.addtime}" style="width: 130px;">
                </dd>
                <dd id="identifier" style="float:right">
                    <label>单据编号:</label>
                    <span id="number">{$info.sn}</span>
                    <i id="editBills"></i>
                    <span class="ui-combo-wrap" id="numberAuto" style="display: none;">
                        <i class="trigger"></i>
                    </span>
                </dd>
            </dl>
            <hr class="hrcls" />
        </div>

        <div class="wrapper_con">
            <span id="config" class="ui-config"><a href="#" class="ui-icon-config-new"></a></span>

            <!-- 表格 -->
            <div class="grid-wrap">
                <table id="grid"></table>
                <div id="page"></div>
            </div>

            <div class="cf" id="bottomField">
                <div class="fr" id="toolBottom">
                    <!-- <a id="savaAndAdd" class="ui-btn ui-btn-sp mrb">保存并新增</a>
                    <a id="save" class="ui-btn">保存</a> -->
                    <span id="groupBtn">
                        <a id="add" class="ui-btn ui-btn-sp mrb">新增</a>
                        <a id="copy" class="ui-btn">复制</a>
                        <a id="savaAndAdd" class="ui-btn">保存</a>
                        <a target="_blank" id="print" class="ui-btn mrb">打印</a>
                    </span>
                </div>
            </div>
        </div>

        <div class="con-footer cf">
            <div class="mb10">
                <textarea type="text" id="note" class="ui-input ui-input-ph" placeholder="暂无备注信息"></textarea>
            </div>
            <div class="cf fr">
                <a href="#" class="linkToCheck ui-btn-bill ui-btn-add mr20"
                    onclick="addPage('/store/costadjustment/index.html','storage_index','成本调整单记录')">历史单据</a>
                <a href="#" id="operaLog" class="ui-btn">操作日志</a>
            </div>
        </div>


        <div id="operaLogBox" class="shadow opera-log-box" style="position: absolute;z-index: 999; display: none;">
            <p class="cf">
            <div class=" mr30"><label>制单人：</label><span id="userName">{$info.by_name}</span></div>
            <div class=""><label>制单时间：</label><span id="createTime">{$info.addtime}</span></div>
            </p>
            <p class="cf">
            <div class=" mr30"><label>最后修改人：</label><span id="modifyName">{$info.editby_name}</span></div>
            <div class=""><label>最后修改时间：</label><span id="modifyTime">{$info.edittime}</span></div>
            </p>
        </div>
    </div>

    <!--  以隐藏的方式获取商品的样式 ，作用是样式 -->
    <div id="pelem_goods" style="display:none;">
        <div class="pr" id="elem_goods"><input type="text" class="textbox  customelement" name="goodsname"
                autocomplete="off"><span class="ui-icon-ellipsis"></span></div>
    </div>

    <!--  以隐藏的方式获取商品的样式 ，作用是赋值 -->
    <div style="display:none;">
        <input type="text" id="goodsname" value="" autocomplete="off" readonly="">
        <input type="text" id="ck1name" value="" autocomplete="off" readonly="">
        <input type="text" id="customerid" value="" autocomplete="off" readonly="">
        <input type="text" id="before_yh_price" value="" autocomplete="off" readonly="">
        <input type="text" id="staffid" value="" autocomplete="off" readonly="">
    </div>

    <!-- 仓库 -->
    <div id="batch" style="display:none;">
        <div class="pr" id="elem_batch">
            <input type="text" class="textbox storageAuto customelement ui-combo-active" name="locationName"
                autocomplete="off" id="1_locationName" style="outline: -webkit-focus-ring-color auto 5px;">
            <span class="ui-icon-triangle-1-s" ></span>
        </div>
    </div>
    <!-- 仓库弹窗 -->
    <div class="ui-droplist-wrap" id="chooseBatch"
        style="position: absolute; top: 231.891px; z-index: 1000; width: 102px; display: none; left: 617px;">
        <div class="droplist" style="position: relative; overflow: auto; min-height: 150px; height: 150px;">
            {volist name="store" id="vo"}
            <div class="list-item" ck_id="{$vo.id}" title="{$vo.name}">{$vo.name}</div>
            {/volist}
        </div>
    </div>
    <!--  以隐藏的方式获取仓库的值 -->
    <div style="display:none;">
        <input type="text" id="batchName" value="" autocomplete="off" readonly="">
        <input type="text" id="store_id" value="" autocomplete="off" readonly="">
        <input type="text" id="id" value="{$id}" autocomplete="off" readonly="">
    </div>
</div>

<script type="text/javascript">
    $(document).ready(function () {
        //获取商品
        $(".grid-wrap").on("click", ".ui-icon-ellipsis", function (e) {
            pre_choose_goods('/admin/basic/choose_goods.html', this);

        });
    });

    function pre_choose_goods(url, obj) {
        choose_goods(url, obj, function (res) {
            if (res.btn == 3 && res.status == 1) {
                //console.log(res);
                var data = res.data;
                if (data.status == 1) {

                    var $count = data.info.count;
                    var good_list = data.info.list;
                    var allIds = $("grid").jqGrid('getDataIDs');
                    var ids = $("#grid").getDataIDs();

                    // console.log("当前行");
                    // console.log(row_id);
                    // console.log("长度："+ids.length);
                    // console.log(ids);
                    row_id = parseInt(row_id);
                    var $cha_id = ids.length - row_id;//最后id-当前id
                    var cha_han = $count - $cha_id - 1;//需要补充的行
                    //console.log("cha:"+cha_han);
                    //补充行
                    if (cha_han > 0) {
                        var mydata1 = [];
                        for (var iii = ids.length; iii < ids.length + cha_han; iii++) {
                            var obj = { id: iii + 1, goodsname: "", dw_name: "", money: "", locationName: "", remark: "" }
                            mydata1.push(obj);
                        }
                        console.log(mydata1);
                        for (var iii = 0; iii <= mydata1.length; iii++) {
                            jQuery("#grid").jqGrid('addRowData', ids.length + iii + 1, mydata1[iii]);
                        }

                    }
                    for (let i = 0; i < $count; i++) {
                        // alert(row_id);
                        $("#grid").jqGrid("saveCell", edit_row, edit_col);
                        $("#grid").jqGrid("setCell", row_id + i, 'goodsname', good_list[i].name);
                        $("#grid").jqGrid("setCell", row_id + i, 'dw_name', good_list[i].dw);
                        $("#grid").jqGrid("setCell", row_id + i, 'money', "0.00");
                        $("#grid").jqGrid("setCell", row_id + i, 'goods_id', good_list[i].id);
                        $("#grid").jqGrid("setCell", row_id + i, 'unit_id', good_list[i].unit_id);
                    }
                    // 合计的变量

                    // var shuliangs = $("#grid").getCol('shuliang', false, 'sum');
                    // layer.close(index);
                } else {
                    layer.msg("获取商品信息失败");
                }
            }
        });


    }
</script>

<script>
    var edit_row = 0;
    var edit_col = 0;
    var row_id = 0;
    var col_name = 0;

    var goods = '<span class="red">*</span>商品<label> -- 扫描枪录入</label><span id="barCodeInsert" class="open" onclick="smq();"><span class="ui-icon-circle"></span></span>';
    var batch = '<span class="red">*</span>仓库<small id="batchStorage1" onclick="batchBtn(1);" class="btns">批量</small>';

    $(document).ready(function () {
        var moneys = 0;
        $("#grid").jqGrid({
            url: '/store/costadjustment/edit.html?ajax=100&id={$id}',
            datatype: "json",//数据来源，本地数据（local，json,jsonp,xml等）
            height: '90%',//高度，表格高度。可为数值、百分比或'auto'
            colNames: ["goods_id", "操作", goods, "单位", "<span class='red'>*</span>调整金额", batch, "备注", "store_id", "unit_id"],
            colModel: [
                { name: 'goods_id', index: '', hidden: true },
                { name: '', index: 'id', width: 60, label: "操作", formatter: cLink },
                {
                    name: "goodsname",
                    label: "商品",
                    width: 300,
                    title: !0,

                    classes: "goods",
                    editable: true,
                    edittype: "custom",
                    editoptions: {
                        custom_element: function (t, e) {
                            $("#pelem_goods").html('<div class="pr" id="elem_goods"><input type="text" value="'+t+'" class="textbox  customelement" name="goodsname" autocomplete="off" ><span class="ui-icon-ellipsis"></span></div>');
                            return $("#elem_goods");
                        },
                        custom_value: function (t, e, a) {
                            var ad = $("#goodsname").val();
                            $("#goodsname").val("");//重置赋值
                            return ad;
                        },
                        handle: function () {

                        },
                        trigger: "ui-icon-ellipsis"
                    }
                },
                { name: 'dw_name', index: '', width: 60, label: "单位", editable: false, },
                { name: 'money', index: '', width: 100, label: "调整金额", align: "right", editable: true, },
                {
                    name: "locationName",
                    label: '<span class="red">*</span>仓库',
                    nameExt: '<small id="batchStorage">批量</small>',
                    width: 100,
                    link: "inventory",
                    editable: !0,
                    edittype: "custom",
                    editoptions: {
                        custom_element: function (t, e) {
                            // return $(".storageAuto")[0]
                            var batch = $("#elem_batch");
                            $("#batch").html('<div class="pr" id="elem_batch"><input type="text" value="'+t+'" class="textbox storageAuto customelement ui-combo-active" name="locationName" autocomplete="off" id="1_locationName" style="outline: -webkit-focus-ring-color auto 5px;"><span class="ui-icon-triangle-1-s"  id="st_id"></span></div>');
                            return batch;
                        },
                        custom_value: function (t, e, a) {
                            var ba = $("#batchName").val();
                            // var ba = "默认仓库";
                            $("#batchName").val("");//重置赋值
                            return ba;
                        },
                        handle: function () {

                        },
                        trigger: "ui-icon-triangle-1-s"
                    }
                },
                { name: 'mark', index: '', width: 150, label: "备注", editable: true, },
                { name: 'store_id', index: '', hidden: true },
                { name: 'unit_id', index: '', hidden: true }
            ],
            cellEdit: true,
            cellurl: '/',
            rowNum: 10,
            rowList: [10, 20, 30],
            sortname: 'id',
            sortorder: "desc",
            pagerpos: "left",//分页位置
            rownumbers: true, //自增序号
            pgbuttons: true,//翻页按钮
            pagination: true,
            altRows: false,
            gridview: !0,
            shrinkToFit: !1,
            cellLayout: 8,
            autowidth: !0,
            pager: "#page",
            viewrecords: !0,
            cmTemplate: {
                sortable: !1,
                title: !1
            },
            loadError: function (t, e, i) {
                parent.Public.tips({
                    type: 1,
                    content: "操作失败了哦，请检查您的网络链接！"
                })
            },
            beforeEditCell: function (rowid, cellname, value, iRow, iCol) {
                col_name = cellname;
                edit_row = iRow;
                edit_col = iCol;
                row_id = rowid;
                var gname = $("#grid").jqGrid("getCell", row_id, 'goodsname');
                $("#goodsname").val(gname);
            },
            beforeSaveCell: function (rowid, cellname, value, iRow, iCol) {
                edit_row = iRow;
                edit_col = iCol;
                row_id = rowid;


                if (cellname == 'money') {
                    moneys = parseFloat($("#grid").getCol('money', false, 'sum')).toFixed(2);
                }
                // 重新设置合计的数量
                $("#grid").footerData('set', { "goodsname": '合计', money: moneys });
            },
            // 合计
            footerrow: true,
            gridComplete: function () {
                moneys = parseFloat($("#grid").getCol('money', false, 'sum')).toFixed(2);
                $("#grid").footerData('set', { "goodsname": '合计', money: moneys });
            },
        });

        var mydata = [];
        for (var i = 0; i < 5; i++) {
            var obj = { goodsname: "", dw_name: "", money: "", locationName: "", remark: "" }
            mydata.push(obj);
        };
        for (var i = 0; i <= mydata.length; i++) {
            jQuery("#grid").jqGrid('addRowData', i + 1, mydata[i]);
        }

    });

    //增加、删除按钮
    function cLink(cellvalue, options, rowObject) {
        return '<div class="operating"><span class="ui-icon ui-icon-plus" title="新增行" onclick="add_row(' + options.rowId + ')" style="margin:0 2px;"></span> <span class="ui-icon ui-icon-trash" onclick="del_row(' + options.rowId + ')" title="删除行" style="margin:0 2px;">删除</span></div>';
    }


    // 选择仓库弹窗
    $(".grid-wrap").on("click", ".ui-icon-triangle-1-s", function (e) {
        var top = $(this).offset().top;
        var left = $(this).offset().left;
        $("#chooseBatch").show();
        $("#chooseBatch").css({ "top": (top + 25) + "px", "left": (left - 80) + "px" })
    })
    // 仓库选择鼠标移入移出
    $(".ui-droplist-wrap .droplist .list-item").hover(function () {
        $(this).addClass("on");
    }, function () {
        $(this).removeClass("on");
    });
    // 点击选择仓库
    $(".ui-droplist-wrap .droplist").on("click", ".list-item", function (e) {
        var title = $(this).attr("title");
        var id = $(this).attr("ck_id");
        $("#batchId").val(id);
        $("#grid").jqGrid("setCell", row_id, 'store_id', id);
        $("#grid").jqGrid("setCell", row_id, 'locationName', title);
        $("#batchName").val(title);
        $("#chooseBatch").hide();
        // alert(title)
    });
    //仓库选择框外点击则隐藏
    $(document).mouseup(function (e) {
        if (e.target.id != "st_id") {
            var con = $("#chooseBatch");   // 设置目标区域
            if (!con.is(e.target) && con.has(e.target).length === 0) {
                $("#chooseBatch").hide();
            }
        }
    });

</script>

<script type="text/javascript">
    $(document).ready(function () {
        // 获取当前日期
        var myDate = new Date;
        var year = myDate.getFullYear(); //获取当前年
        var mon = myDate.getMonth() + 1; //获取当前月
        var date = myDate.getDate(); //获取当前日
        // console.log(year + '-' + mon + '-' + date)
        if (mon < 10) {
            mon = "0" + mon;
        }
        if (date < 10) {
            date = "0" + date;
        }
        $("#date").val(year + '-' + mon + '-' + date);


        // 操作日志鼠标移入移除
        $("#operaLog").hover(function () {
            var top = $(this).offset().top;
            // var left = $(this).offset().left;
            $("#operaLogBox").show();
            $("#operaLogBox").css({ "right": "30px", "top": (top + 20) + "px" })
        }, function () {
            $("#operaLogBox").hide();
        })

    });

    // 表头扫描枪录入的开关
    function smq() {

        if ($("#barCodeInsert").hasClass("close")) {
            $("#barCodeInsert").addClass('open');
            $("#barCodeInsert").removeClass('close');//removeClass
        } else {
            if ($("#barCodeInsert").hasClass("open")) {
                $("#barCodeInsert").addClass('close');
                $("#barCodeInsert").removeClass('open');//removeClass
            }
        }

    }

    $(".wrapper").on("click", "#savaAndAdd", function (e) {
        //先保存
        if (edit_row != 0 && edit_col != 0) {
            $("#grid").jqGrid("saveCell", edit_row, edit_col);
            edit_row = 0;
            edit_col = 0;
        }
        savedata();
    })

    function savedata() {
        var movedata = getJQAllData($("#grid"));

        var flag = 0;
        var hasuser = 0;
        var hasuser1 = 0;
        var indexArr = [];
        // console.log(movedata);
        movedata.forEach(function (self, index) {
            // console.log(self);
            if (self.goodsid != null || self.goodsid != "") {
                hasuser = hasuser + 1;
                if (self.store_id == null || self.store_id == "") {
                    
                    flag = 1;
                    indexArr.push(index);
                    return false;
                } else {
                    hasuser1 = hasuser1 + 1;
                }
            }
        });
        if (hasuser == 0) {
            layer.msg("请选择商品");
            // 必填项（商品）
            // editFun(1, 2, 'grid', 'goodsname', 'goodsName');
            $("#grid").editCell(1, 3, true);
            return false;
        }

        if (flag == 1) {
            layer.msg("请选择仓库");
            // 必填项（仓库）
            $("#grid").editCell(indexArr[0] + 1, 6, true);
            return false;
        }


        var addtime = $("#date").val();
        var mark = $("#note").val();
        var sn = $('#number').text();
        var id = $('#id').val();

        $.ajax({
            type: 'POST',
            url: "update.html",
            data: { id: id, addtime: addtime, sn: sn, mark: mark, movedata: movedata },
            dataType: "json",
            async: false,
            error: function (request) {
                layer.msg("发送请求失败！");
            },
            success: function (data) {
                if (data.status == 1) {
                    layer.msg(data.msg);
                } else {
                    layer.msg(data.msg);
                }
            }
        });
    }

    function getJQAllData(obj) {
        //获取grid表中所有的rowid值
        var rowIds = obj.getDataIDs();
        //初始化一个数组arrayData容器，用来存放rowData
        var arrayData = new Array();

        if (rowIds.length > 0) {
            for (var i = 0; i < rowIds.length; i++) {
                if (Object.values(obj.getRowData(rowIds[i]))[0] != '') {
                    arrayData.push(obj.getRowData(rowIds[i]));
                }
            }
        }
        return arrayData;
    }
</script>

{include file="admin@public/footer" /}